import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:top_foundation/utils/util.dart';

import 'config.dart';

T? _ambiguate<T>(T? value) => value;

class IWindowContainer extends StatefulWidget {
  const IWindowContainer({
    Key? key,
    this.duration,
    this.child,
    this.completer,
    this.alignment = Alignment.center,
    this.isPan = false,
  }) : super(key: key);
  final Completer<void>? completer;
  final Widget? child;
  final Duration? duration;
  final AlignmentGeometry alignment;
  final bool isPan;
  @override
  State<IWindowContainer> createState() => _IWindowContainerState();
}

class _IWindowContainerState extends State<IWindowContainer>
    with SingleTickerProviderStateMixin {
  Size? _size;
  Offset? _orign;
  Offset? _position;

  Offset start = Offset.zero;

  final GlobalKey childKey = GlobalKey();

  late AnimationController ac;

  bool get isPersistentCallbacks =>
      _ambiguate(SchedulerBinding.instance)!.schedulerPhase ==
      SchedulerPhase.persistentCallbacks;
  @override
  void initState() {
    if (!mounted) return;
    ac = AnimationController(vsync: this)
      ..duration = widget.duration ?? const Duration(milliseconds: 200)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          bool isCompleted = widget.completer?.isCompleted ?? false;
          if (status == AnimationStatus.completed && !isCompleted) {
            widget.completer?.complete();
          }
        }
      });
    show(true);

    super.initState();
  }

  Future<void> show(bool animation) {
    if (isPersistentCallbacks) {
      Completer<void> completer = Completer<void>();
      _ambiguate(SchedulerBinding.instance)!.addPostFrameCallback(
          (_) => completer.complete(ac.forward(from: animation ? 0 : 1)));
      return completer.future;
    } else {
      return ac.forward(from: animation ? 0 : 1);
    }
  }

  Future<void> dismiss(bool animation) {
    if (isPersistentCallbacks) {
      Completer<void> completer = Completer<void>();
      _ambiguate(SchedulerBinding.instance)!.addPostFrameCallback(
          (_) => completer.complete(ac.reverse(from: animation ? 1 : 0)));
      return completer.future;
    } else {
      return ac.reverse(from: animation ? 1 : 0);
    }
  }

  @override
  void dispose() {
    ac.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: Stack(
        alignment: widget.alignment,
        children: [
          Positioned(
            top: _position?.dy ?? _orign?.dy,
            left: _position?.dx ?? _orign?.dx,
            key: childKey,
            child: GestureDetector(
              onPanStart: (details) {
                start = details.localPosition;
                final box =
                    childKey.currentContext?.findRenderObject() as RenderBox?;
                _orign = box?.localToGlobal(Offset.zero);
                _size = box?.size;
              },
              onPanUpdate: (details) {
                if (_orign == null) {
                  return;
                }
                var x = details.localPosition.dx - start.dx;
                var y = details.localPosition.dy - start.dy;
                if (widget.isPan) {
                  _position = Offset(
                      max(min(1.sw - _size!.width, _orign!.dx + x), 0),
                      max(
                          min(
                              _orign!.dy + y,
                              1.sh -
                                  (MediaQuery.of(context).viewPadding.bottom) -
                                  _size!.height),
                          MediaQuery.of(context).viewPadding.top - 56));
                  setState(() {});
                }
              },
              child: AnimatedBuilder(
                  animation: ac,
                  builder: (ctx, child) {
                    return Opacity(
                      opacity: ac.value,
                      child: IgnorePointer(
                        ignoring: false,
                        child: Padding(
                          padding: IWindowConfig.margin ?? EdgeInsets.zero,
                          child: widget.child!,
                        ),
                      ),
                    );
                  }),
            ),
          )
        ],
      ),
    );
  }
}
